﻿/*
Commerce by Onex – eCommerce software platform (www.ecommerce.byonex.com)
Copyright (C) 2008-2010 by Onex Group

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 
 */
using System;
using System.Collections.Generic;
using System.Text;
using ShopModel;
using System.Web.UI.WebControls;
using System.Resources;
using System.Reflection;
using CrystalDecisions.CrystalReports.Engine;
using System.Data;
using System.Collections;
using System.IO;
using System.Globalization;
using System.Web;
using System.Configuration;
using System.Xml;

namespace ShopBLL
{
    public static class CommonTools
    {
        #region CONSTANT

        public const string LANGUAGE_KEY_SESSION = "LanguageKeySession";

        #endregion

        #region FIELDS

        private static ResourceManager rm;
        private static NumberFormatInfo numberProvider;

        #endregion

        #region CONSTRUCTORS

        static CommonTools()
        {
            rm = new ResourceManager("Resources.Language", Assembly.Load("App_GlobalResources"));
            numberProvider = CultureInfo.GetCultureInfo("pl-PL").NumberFormat;
        }

        #endregion

        #region PROPERTIES

        public static int? CurrentLanguageID
        {
            get
            {
                if (HttpContext.Current.Session != null)
                {
                    object key = HttpContext.Current.Session[LANGUAGE_KEY_SESSION];
                    if (key != null)
                    {
                        return (int)key;
                    }
                }

                return GetCurrentLanguageID();
            }
        }

        public static NumberFormatInfo NumberProvider
        {
            get
            {
                return numberProvider;
            }
        }

        #endregion

        #region METHODS

        public static ListItem[] FillCategoryTree(Category category, DropDownList ddlCategory, bool withSubcategories)
        {
            List<ListItem> list = null;
            ListItem[] result = null;
            CreateCategoryTree(category, ref list, "", withSubcategories);
            list.Sort(delegate(ListItem left, ListItem rigth) { return left.Text.CompareTo(rigth.Text); });
            result = list.ToArray();
            ddlCategory.Items.AddRange(result);

            return result;
        }

        public static string ConvertAmountToText(decimal Amount)
        {
            return ConvertIntegerToText((int)Amount) + " " + rm.GetString("Currency") + ". " + ConvertIntegerToText((int)((Amount - Decimal.Truncate(Amount)) * 100)) + " " + rm.GetString("CurrencyCent") + ".";
        }

        public static string ProductsPictureDirectory(int productId)
        {
            System.Text.StringBuilder result = new System.Text.StringBuilder();

            if (productId > 0)
            {
                foreach (char digit in productId.ToString())
                {
                    result.Append("/");
                    result.Append(digit);
                }
            }

            return result.ToString();
        }

        public static string GetStatusString(int StatusID)
        {
            switch (StatusID)
            {
                case -1: return rm.GetString("cmsOrdersListAll");
                case 1: return rm.GetString("ForAcceptation");
                case 2: return rm.GetString("NoPayment");
                case 3: return rm.GetString("ToSend");
                case 4: return rm.GetString("Finished");
                case 5: return rm.GetString("PaymentCanceled");
                case 6: return rm.GetString("OrderCanceled");
                case 7: return rm.GetString("Returned");
                default: return rm.GetString("Unknown");
            }
        }

        public static string GetVoucherTypeString(int TypeId)
        {
            switch (TypeId)
            {
                case -1: return rm.GetString("None");
                case 1: return rm.GetString("FreeShipment");
                case 2: return rm.GetString("PercentVoucher");
                case 3: return rm.GetString("ValueVoucher");
                default: return rm.GetString("Unknown");
            }
        }

        public static string GetPaymentString(int paymentId)
        {
            switch (paymentId)
            {
                case 1:
                    return rm.GetString("ShipmentWithPay");

                case 2:
                    return rm.GetString("Transfer");

                case 3:
                    return rm.GetString("Instalements");

                default:
                    if (paymentId > 3)
                    {
                        return rm.GetString("OnlinePayment");
                    }
                    else
                    {
                        return string.Empty;
                    }

            }
        }

        public static string CheckIDsList(string IDs)
        {
            string[] tmp = IDs.Split(',');
            int tmpID = -1;
            string result = string.Empty;
            foreach (string i in tmp)
            {
                if (Int32.TryParse(i, out tmpID))
                {
                    result += i + ",";

                }
            }
            return result.Substring(0, result.Length - 1);
        }

        public static void CreateCategoryTree(Category category, ref List<ListItem> list, string root, bool withSubCategories)
        {
            if (list == null)
            {
                list = new List<ListItem>();
            }
            if (category != null)
            {
                if (category.Children.Count > 0)
                {
                    foreach (Category cat in category.Children)
                    {
                        if (cat.Children.Count > 0)
                        {
                            if (withSubCategories)
                            {
                                list.Add(new ListItem(root + cat.Name, cat.IDcategory.ToString()));
                            }
                            CreateCategoryTree(cat, ref list, root + cat.Name + " / ", withSubCategories);
                        }
                        else
                            list.Add(new ListItem(root + cat.Name, cat.IDcategory.ToString()));
                    }
                }
            }
        }

        public static void CreateCategoryTree(Category c, List<DictionaryValue> list, string root, bool withSubCategories)
        {
            if (c != null)
            {
                if (c.Children.Count > 0)
                {
                    foreach (Category cat in c.Children)
                    {
                        if (cat.Children.Count > 0)
                        {
                            if (withSubCategories)
                                list.Add(new DictionaryValue(cat.IDcategory, root + cat.Name));

                            CreateCategoryTree(cat, list, root + cat.Name + " / ");
                        }
                        else
                            list.Add(new DictionaryValue(cat.IDcategory, root + cat.Name));
                    }
                }
            }
        }

        public static void CreateCategoryTree(Category c, List<DictionaryValue> list, string root)
        {
            if (c != null)
            {
                if (c.Children.Count > 0)
                {
                    foreach (Category cat in c.Children)
                    {
                        if (cat.Children.Count > 0)
                        {
                            CreateCategoryTree(cat, list, root + cat.Name + " / ");
                        }
                        else
                            list.Add(new DictionaryValue(cat.IDcategory, root + cat.Name));
                    }
                }
            }
        }

        private static string ConvertIntegerToText(int Number)
        {
            if (Number == 0)
                return rm.GetString("Zero");

            String[] prim = { "", rm.GetString("One"), rm.GetString("Two"), rm.GetString("Three"), rm.GetString("Four"), rm.GetString("Five"), rm.GetString("Six"), rm.GetString("Seven"), rm.GetString("Eight"), rm.GetString("Nine") };
            String[] _teen = { rm.GetString("Ten"), rm.GetString("Eleven"), rm.GetString("Twelve"), rm.GetString("Thirteen"), rm.GetString("Fourteen"), rm.GetString("Fifteen"), rm.GetString("Sixteen"), rm.GetString("Seventeen"), rm.GetString("Eighteen"), rm.GetString("Nineteen") };
            String[] _ty = { "", rm.GetString("Ten"), rm.GetString("Twenty"), rm.GetString("Thirty"), rm.GetString("Forty"), rm.GetString("Fifty"), rm.GetString("Sixty"), rm.GetString("Seventy"), rm.GetString("Eighty"), rm.GetString("Ninety") };
            String[] hundred = { "", rm.GetString("OneHundred"), rm.GetString("TwoHundred"), rm.GetString("ThreeHundred"), rm.GetString("FourHundred"), rm.GetString("FiveHundred"), rm.GetString("SixHundred"), rm.GetString("SevenHundred"), rm.GetString("EightHundred"), rm.GetString("NineHundred") };
            String[] postfix = { "", rm.GetString("Thousand"), rm.GetString("Million"), rm.GetString("Bilion"), rm.GetString("Trillion"), rm.GetString("Billiards") };

            StringBuilder result = new StringBuilder();

            Stack<int> sNumber = new Stack<int>();
            int[] tNumber = new int[3];
            int tmpNumber;

            if (Number < 0)
                result.Append(rm.GetString("Minus"));

            while (Number > 0)
            {
                sNumber.Push(Number % 1000);
                Number /= 1000;
            }

            while (sNumber.Count > 0)
            {
                tmpNumber = sNumber.Pop();

                for (int i = 0; i < 3; i++)
                {
                    tNumber[i] = tmpNumber % 10;
                    tmpNumber /= 10;
                }

                if (tNumber[2] > 0)
                    result.Append(hundred[tNumber[2]] + " ");

                if (tNumber[1] == 1)
                {
                    result.Append(_teen[tNumber[0]] + " ");
                }
                else
                {
                    if (tNumber[1] > 0)
                    {
                        result.Append(_ty[tNumber[1]] + " ");
                        result.Append(prim[tNumber[0]] + " ");
                    }
                    else
                    {
                        if (tNumber[0] > 0)
                            result.Append(prim[tNumber[0]] + " ");
                    }
                }

                if (sNumber.Count > 0)
                {
                    result.Append(postfix[sNumber.Count] + " ");
                }
            }
            rm.ReleaseAllResources();
            return result.ToString();
        }

        public static int? GetCurrentLanguageID()
        {
            List<Language> AvailableLanguages = ReportsManager.Instance.GetAvailableLanguages(true);

            foreach (Language l in AvailableLanguages)
            {
                if (l.Culture == System.Threading.Thread.CurrentThread.CurrentUICulture.Name || l.Culture.StartsWith(System.Threading.Thread.CurrentThread.CurrentUICulture.Name))
                    return l.LanguageID;
            }

            return null;
        }

        public static void SetCurrentLanguageID()
        {
            List<Language> AvailableLanguages = ReportsManager.Instance.GetAvailableLanguages(true);

            foreach (Language l in AvailableLanguages)
            {
                if (l.Culture == System.Threading.Thread.CurrentThread.CurrentUICulture.Name || l.Culture.StartsWith(System.Threading.Thread.CurrentThread.CurrentUICulture.Name))
                {
                    HttpContext.Current.Session[LANGUAGE_KEY_SESSION] = l.LanguageID;
                }
            }
        }

        public static string ToString(bool value)
        {
            ResourceManager rm = new ResourceManager("Resources.Language", Assembly.Load("App_GlobalResources"));

            if (value)
            {
                return rm.GetString("Yes"); ;
            }
            else
            {
                return rm.GetString("No");
            }
        }

        public static string CreateAddress(string street, string zipCode, string city)
        {
            return street + "<br />" + zipCode + " " + city;
        }

        public static string GeneratePageFooter()
        {
            return ReportsManager.Instance.GetContentTemplate("PageFooter", CommonTools.CurrentLanguageID).Content;
        }

        public static string GenerateTitleTag()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("<title>");
            sb.Append(ReportsManager.Instance.GetContentTemplate("TitleTag", CommonTools.CurrentLanguageID).Content);
            sb.Append("</title>");
            return sb.ToString();

        }

        public static InstallationStatus GetInstallationStatus()
        {
            switch (ConfigurationManager.AppSettings["InstallationStatus"])
            {
                case "NotInstalled": return InstallationStatus.NotInstalled;
                case "Installed": return InstallationStatus.Installed;
                default: return InstallationStatus.NotInstalled;
            }
        }

        public static bool UpdateInstallationStatus(InstallationStatus Status)
        {
            try
            {
                string _path = HttpContext.Current.Server.MapPath("~");

                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(_path + "//web.config");

                XmlNode x = xmlDoc.SelectSingleNode("//configuration/location/appSettings/add[@key='InstallationStatus']");

                x.Attributes.Remove(x.Attributes["value"]);
                XmlAttribute newAtt = xmlDoc.CreateAttribute("value");
                newAtt.Value = Status.ToString();
                x.Attributes.Append(newAtt);

                xmlDoc.Save(_path + "//web.config");
            }
            catch
            {
                return false;
            }

            return true;
        }

        #endregion

        #region ENUMS
        
        public enum InstallationStatus
        {
            NotInstalled = 0,
            Installed = 1
        }
        
        #endregion EUNMS
    }
}
